package com.niodata.dp.monitor.sharelib.service;

import com.niodata.dp.monitor.sharelib.entity.base.BaseResult;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component("timelyRateService")
public class TimelyRateService {

  @Autowired
  private RestTemplate restTemplate;

  @Value("${monitor.server.address}")
  private String server;
  @Value("${monitor.server.port}")
  private String port;

  //数据及时率查询
  public BaseResult listDataTimelyRates(Long userId, String monitorId, int checkPoint,
        double threshold, int offset, int count) {
    monitorId = monitorId == null ? "" : monitorId;

    String execUrl = String.format(
          "http://%s:%s/monitor/file/timeliness/list?userId=%s&monitorId=%s"
                + "&checkPoint=%s&threshold=%s&offset=%s&count=%s",
          server, port, userId, monitorId, (checkPoint > 0 ? checkPoint : ""),
          (threshold > 0 ? threshold : ""), offset, count);
    return restTemplate
          .getForEntity(execUrl, BaseResult.class)
          .getBody();
  }

  public BaseResult listTimelyRatesByTimeRange(String monitorId, int checkPoint, Date startTime,
        Date endTime) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    monitorId = monitorId == null ? "" : monitorId;
    String startTimeStr = startTime == null ? "" : format.format(startTime);
    String endTimeStr = endTime == null ? "" : format.format(endTime);
    String execUrl = String.format(
          "http://%s:%s/monitor/file/timeliness/range?monitorId=%s&checkPoint=%s&startTime=%s&endTime=%s",
          server, port, monitorId, (checkPoint > 0 ? checkPoint : ""), startTimeStr,
          endTimeStr);
    return restTemplate
          .getForEntity(execUrl, BaseResult.class)
          .getBody();
  }
}
